package edu.fim.data.dao;

import java.util.ResourceBundle;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import edu.fim.data.dao.exception.DAOException;
import edu.fim.presentation.model.bean.Consumer;

public class ConsumerDAO extends AbstractDAO<Consumer, Integer> {
	
	private static ResourceBundle bundle = ResourceBundle.getBundle("META-INF/properties/ConsumerSQL");

	public ConsumerDAO(EntityManager entityManager) {
		super(entityManager, Consumer.class);
	}

	public Consumer findByUserAndPassword(String username, String password) throws DAOException {
		String sql = bundle.getString("findByUsernameAndPassword");
		Query query = getEntityManager().createQuery(sql);
		query.setParameter("username", username);
		query.setParameter("password", password);
		try {
			return (Consumer) query.getSingleResult();
		} catch (NoResultException e) {
			throw new DAOException("Invalid user or password.", e);
		}
	}
	
	public void updateCaloriesThreshold(Consumer consumer, Double newThreshold) {
		Consumer managedEntity = findById(consumer.getId());
		managedEntity.setCaloriesThreshold(newThreshold);
	}
}